package org.springblade.common.utils.message;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @Author ysq
 * @Date 2024/11/12
 * @Description 开放接口签名生成工具类
 */
public class SignUtils {

    /**
     * 生成签名sign,通过appid,nonce,timestamp,secret进行签名
     * 加密前：appidsidaWh6bF4rcljb1MJvOnonce23983997secret843c7f7c42de18459d293c42656734aac96a876ctimestamp1729234114242
     * 加密后：1B5E38136AA1DB5BD096D72F48B695AF9F1A5D47
     * @param params 入参
     * @return 签名
     */
    public static String createSign(Map<String, String> params) {
        // 创建一个TreeMap，这样键会自动按升序排序
        SortedMap<String, Object> sortedParams = new TreeMap<>(params);
        // 构造请求参数字符串
        StringBuilder requestParamsString = new StringBuilder();
        for (Map.Entry<String, Object> entry : sortedParams.entrySet()) {
            requestParamsString.append(entry.getKey()).append(entry.getValue());
        }

		// 进行SHA1运算
        try {
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] digest = md.digest(requestParamsString.toString().getBytes());

            // 将二进制数组转换为十六进制的字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : digest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }

            // 返回签名
            return hexString.toString().toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            // SHA1算法应该总是可用的，但如果出现异常，则抛出
            throw new RuntimeException("SHA1 algorithm is not available", e);
        }
    }

}

